const iconv = require("iconv-lite");

/**
 * 在数字前补0
 */
function padding0(num, length) {
    for (let len = (num + "").length; len < length; len = num.length) {
        num = "0" + num;
    }
    return num;
}

function normalize(originalName) {
    return iconv.encode(originalName, 'gbk').toString('binary');
}

/**
 *
 * @param txt 解析gb28181的content字段
 */
function sipContent2Object(txt) {
    const array = txt.split('\r\n');
    let obj = {};
    for (let i = 0; i < array.length; i++) {
        const tmp = array[i].split('=');
        obj[tmp[0]] = tmp[1];
    }
    return obj;
}

/**
 * 获取UDP空闲端口
 */
function freeUdpPort(camera_id, channelIndex=1) {
    const basePort = 40000;
    if (!channelIndex) channelIndex = 1;
    return basePort + camera_id * 10 + channelIndex;

}

/**
 * 去掉最前面的一个符号
 * @param str
 * @param prefix 要去掉的符号
 * @return {*|string}
 */
function removePrefix(str, prefix='/') {
    if (str.indexOf(prefix) === 0) {
        return str.substring(prefix.length);
    } else {
        return str;
    }
}

module.exports = {

    gb2312ToUtf8(input) {
        let bufs = iconv.decode(input, 'gb2312');
        return [bufs.toString('utf8')];
    },
    padding0,
    normalize,
    sipContent2Object,
    freeUdpPort,
    removePrefix
}